import restDataMain from '@/utils/response'
/**
 * 判断用户浏览器是否为IE
 */
export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}
//深拷贝
export function deepClone(obj) {
  let _tmp = JSON.stringify(obj) //将对象转换为json字符串形式
  let result = JSON.parse(_tmp) //将转换而来的字符串转换为原生js对象
  return result
}
export function transformTimestamp(timestamp) {
  let a = new Date(timestamp).getTime()
  const date = new Date(a)
  const Y = date.getFullYear() + '-'
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '  '
  const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
  const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  // const s = date.getSeconds(); // 秒
  const dateString = Y + M + D + h + m + s
  return dateString
}
// 上传文件二次校验,判断是否符合上传文件格式要求
/**
 *
 * @param {Object} file 上传的文件对象
 * @param {Array} acceptArry 上传的文件格式
 * @param {number} size 上传的文件大小
 * @returns string/true/false
 */
//判断文件的上传格式和大小
export function $checkFileType(
  file,
  acceptArry = ['.doc', '.xls', '.ppt', '.txt', '.pdf'],
  size = 20
) {
  const testmsg = file.name.substring(file.name.lastIndexOf('.'))
  let isRType = false
  const isLt20M = file.size / 1024 / 1024 <= size
  if (!acceptArry.includes(testmsg)) {
    isRType = false
    return `请上传${acceptArry.join(',')}格式的附件`
  }
  isRType = true

  if (!isLt20M) {
    return `上传附件大小不能超过${size}MB`
  }
  return isRType && isLt20M
}

//判断文件类型，选择相应图标
export function getFileIcon(url) {
  let pdfReg = /^.+(\.pdf)$/
  let txtReg = /^.+(\.txt)$/
  let wordReg = /^.+(\.doc|\.docx|\.wps)$/
  let pptReg = /^.+(\.ppt|\.pptx)$/
  let excelReg = /^.+(\.xls|\.xlsx)$/
  let jpgReg = /^.+(\.png|\.jpg|\.jpeg|\.bmp|\.gif)$/
  if (pdfReg.test(url)) {
    return 'icon-pdf'
  }
  if (txtReg.test(url)) {
    return 'icon-txt'
  }
  if (wordReg.test(url)) {
    return 'icon-word'
  }
  if (pptReg.test(url)) {
    return 'icon-ppt'
  }
  if (excelReg.test(url)) {
    return 'icon-excel'
  }
  if (jpgReg.test(url)) {
    return 'icon-tupianpicture'
  }
  return 'icon-xiangguanziliaolianjie'
}
export const getTypeName = (v, map = [], { label = 'label', value = 'value' } = {}) => {
  let name = ''
  try {
    const type = map.find((item) => String(item[value]) === String(v))
    if (type) {
      name = type[label]
    }
  } catch (e) {
    console.error(e)
  }
  return name
}
//关闭页面时判断文件数组中的fileId是否相等
export const $U_arr_isDif = (arr1, arr2) => {
  // debugger
  const a = arr1.length !== arr2.length
  const arry = []
  arr1.forEach((item) => {
    arry.push(item.fileid || item.fileId)
  })
  const b = arr2.filter((item) => !arry.includes(item.fileid))
  return a && b
}
//判断两个复杂数据（对象，数组，常量...）是否相等
export const $U_isEqual = (a, b) => {
  if (a === b) return true
  let isObjectA = isObject(a)
  let isObjectB = isObject(b)
  if (isObjectA && isObjectB) {
    try {
      let isArrayA = Array.isArray(a)
      let isArrayB = Array.isArray(b)
      if (isArrayA && isArrayB) {
        // a b都是数组
        return (
          a.length === b.length &&
          a.every((el, index) => {
            return $U_isEqual(el, b[index])
          })
        )
      } else if (a instanceof Date && b instanceof Date) {
        // a b都是Date对象
        return a.getTime() === b.getTime()
      } else if (!isArrayA && !isArrayB) {
        // 此时a b都是纯对象
        let keyA = Object.keys(a)
        let keyB = Object.keys(b)
        return keyA.length === keyB.length && keyA.every((key) => $U_isEqual(a[key], b[key]))
      } else {
        return false
      }
    } catch (e) {
      console.log(e)
      return false
    }
  } else if (!isObjectA && !isObjectB) {
    // a b 可能是string，number，boolean，undefined中的一种
    return String(a) === String(b)
  } else {
    return false
  }
}
function isObject(obj) {
  return typeof obj === 'object' && obj !== null
}

//自动补全小数
export const decimalComp = (num, digit = 2) => {
  //num是数值；digit是保留有效数字位数
  let nums = (num || 0).toString().split('.')
  return nums[0] + '.' + (nums[1] || '0').padEnd(digit, '0')
}
// 音乐时长过滤
export const formatTime = (time) => {
  const minutes = Math.floor((time % 3600) / 60)
  const seconds = Math.floor(time % 60)
  const milliseconds = Math.floor((time - Math.floor(time)) * 1000)
  return `${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
}
/**
 * 防抖
 */
let timeout = null
export const debounce = (callback, time = 500) => {
  console.log(123)
  return function () {
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(callback, time)
  }
}
//监听webview返回的消息
export const watchWebview = async () => {
  try {
    //window环境下
    if (window.chrome && window.chrome.webview) {
      window.chrome.webview.addEventListener('message', function (event) {
        restDataMain.value = event.data
      });
    }
    //麒麟linux系统qt环境下
    if (window.qt) {
      await getSendObject();
      window.sendObject.sendMessage.connect(function (data) {
        //alert('接收到消息' + data)
        restDataMain.value = JSON.parse(data)
      });
    }
  } catch (e) {
    alert(e)
  }
}

//获取麒麟系统qt交互对象
export const getSendObject = () => {
  return new Promise((resolve, reject) => {
    if (window.qt) {
      new QWebChannel(window.qt.webChannelTransport, function (channel) {
        // 从QWebChannel对象中获取在Web页面中定义的对象 
        window.sendObject = channel.objects.sendObject;
        resolve('获取sendObject对象成功')
      })
    }
  })
}
//解析token
export const jwtDecode = (token) => {
  let strings = token.split(".");
  let userinfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))));
  return userinfo
}
